package yana.tpe.onlineshop.controller;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import static yana.tpe.onlineshop.controller.AbstractController.CATEGORY;
import static yana.tpe.onlineshop.controller.AbstractController.ID;
import yana.tpe.onlineshop.domain.domains.Category;
import yana.tpe.onlineshop.domain.domains.Comment;
import yana.tpe.onlineshop.domain.domains.Product;
import yana.tpe.onlineshop.services.CategoryService;
import yana.tpe.onlineshop.services.CommentService;
import yana.tpe.onlineshop.services.ProductService;

/**
 *
 */
@Controller
@RequestMapping(method = RequestMethod.GET)
public class ShopController extends AbstractController {

    @Autowired
    private CategoryService categoryService;
    
    @Autowired
    private ProductService productService;

    @Autowired
    private CommentService commentService;

    @RequestMapping()
    public String root(HttpServletRequest request) {
        logger.debug("Try to get root");
        return "redirect:" + request.getRequestURI() + CATEGORY + ROOT;
    }


    @RequestMapping(value = CATEGORY)
    public String categoryRoot(HttpServletRequest request) {
        logger.debug("Try to get root category");
        return getRedirectBaseUrl(request, CATEGORY) + ROOT;
    }

    @RequestMapping(value = CATEGORY + ID + PRODUCT + CHILD, method = RequestMethod.GET)
    public ModelAndView product(HttpServletRequest request, 
            @PathVariable String id, @PathVariable String child) {
        logger.debug("Try to get child categories for [id={}]", id);

        Category category = getCategory(categoryService, id);
        logger.debug("Current category is {}", category);

        Product product = productService.getWithComments(Integer.parseInt(child));
        logger.debug("Current product is {}", product);
        
        if (product.getCategory() != null) {
            category = product.getCategory();
        }

        ModelAndView mav = new ModelAndView("/home");
        mav.addObject("categoriesTree", categoryService.getCategoryForEdit());
        mav.addObject("categoriesNavigation", categoryService.getCategoryWithParents(
                category != null ? category.getId() : null));
        mav.addObject("product", product);
        mav.addObject("productComments", product.getComments());
        mav.addObject("category_id", getCategoryId(category));
        logger.debug("ModelAndView is {}", mav);

        return mav;
    }


    @RequestMapping(value = CATEGORY + ID, method = RequestMethod.GET)
    public ModelAndView category(HttpServletRequest request, @PathVariable String id) {
        logger.debug("Try to get child categories for [id={}]", id);

        Category category = getCategory(categoryService, id);
        logger.debug("Current category is {}", category);

        ModelAndView mav = new ModelAndView("/home");
        mav.addObject("categoriesTree", categoryService.getCategoryForEdit());
        mav.addObject("categoriesNavigation", categoryService.getCategoryWithParents(
                category != null ? category.getId() : null));
        mav.addObject("products", productService.getProductFromCategory(category));
        mav.addObject("category_id", getCategoryId(category));
        logger.debug("ModelAndView is {}", mav);

        return mav;
    }
    
    @RequestMapping(value = CATEGORY + ID + PRODUCT + CHILD + ADD + COMMENT, method = RequestMethod.POST)
    public String addComment(HttpServletRequest request, @PathVariable String id, 
                @PathVariable Integer child, @RequestParam String description) {
        commentService.addComment(child, new Comment(description));
        return getRedirectBaseUrl(request, CATEGORY) + ID + PRODUCT + CHILD;
    }

    @RequestMapping(value = "/product/{id}/image")
    public ResponseEntity<byte[]> image(HttpServletRequest request, 
                @PathVariable() int id) throws IOException {
        logger.debug("Try to get image for product [id={}]", id);

        Product get = productService.getWithImage(id);
        if (get == null) {
            logger.error("Product not found");
            return new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND);
        }

        byte[] data = get.getImage();

        if (data == null || data.length == 0) {
            logger.error("Product does not has image");
            data = IOUtils.toByteArray(ShopController.class.getResourceAsStream("/images/image_not_found.png"));
        }


        HttpHeaders responseHeaders = new HttpHeaders();
//        responseHeaders.setContentType(MediaType.IMAGE_PNG);
        responseHeaders.setContentLength(data.length);
        responseHeaders.set("Content-Disposition", "attachment");
        return new ResponseEntity<byte[]>(data, responseHeaders, HttpStatus.OK);
    }
}
